package cn.net.isir.utils;

import cn.net.isir.entity.Organizations;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author liuxubo
 * @filename StringUtils.java
 * @package cn.net.isir.common
 * @email lxb@isir.net.cn
 * @date 2018/09/10
 * @comment
 * @since 1.7
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {
    // 声明log4j日志
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(StringUtils.class);


    /**
     * 返回32位随机字符串
     *
     * @return 返回32位随机字符串
     */
    public static String randomUUID() {
        return String.valueOf(UUID.randomUUID()).replaceAll("-", "").toLowerCase();
    }


    /**
     * 返回32位随机字符串
     *
     * @return 返回32位随机字符串
     */

    /**
     * 返回32位随机字符串
     *
     * @param length 规定位数
     * @return 返回规定位数的字符串
     */
    public static String randomUUID(int length) {
        String random = randomUUID();
        if (length < random.length()) {
            return random.substring(0, length);
        }
        return random;
    }

    /**
     * 返回大写的32位随机字符串
     *
     * @return 返回大写的32位随机字符串
     */
    public static String randomUUIDUpperCase() {
        return randomUUID().toUpperCase();
    }

    /**
     * 返回规定位数的大写随机字符串
     *
     * @param length 位数
     * @return 长度
     */
    public static String randomUUIDUpperCase(int length) {
        return randomUUID(length).toUpperCase();
    }

    /**
     * 根据时间生成32位随机字符串
     *
     * @return 13位时间戳-7位随机数-7位随机数-循环补位
     */
    public static String randomByTime() {
        StringBuilder sb = new StringBuilder();
        sb.append(System.currentTimeMillis());
        while (32 - sb.length() > 0) {
            sb.append("-");
            String num = String.valueOf(+Math.floor(Math.random() * Math.pow(10, 7)));
            sb.append(num, 0, num.length() - 2);
        }
        return sb.substring(0, 32);
    }

    /**
     * 根据时间生成32位随机字符串
     *
     * @return 13位时间戳-7位随机数-7位随机数-循环补位
     */
    public static String randomByTime2() {
        StringBuilder sb = new StringBuilder();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd-HHmm");
        sb.append(simpleDateFormat.format(System.currentTimeMillis()));
        sb.append("-");
        sb.append(System.currentTimeMillis());
        while (32 - sb.length() > 0) {
            sb.append("-");
            String num = String.valueOf(+Math.floor(Math.random() * Math.pow(10, 7)));
            sb.append(num, 0, num.length() - 2);
        }
        return sb.substring(0, 32);
    }

    /**
     * 返回一个随机数字
     *
     * @param length     长度
     * @param repeatable 是否可重复; false表示不可重复; 如果此处传入false,但是length>10,则此参数失效
     * @return 随机数字
     */
    public static String randomNumber(int length, boolean repeatable) {
        Random random = new Random();
        StringBuilder result = new StringBuilder();
        while (result.length() < length) {
            String n = String.valueOf(random.nextInt(10));
            if (!repeatable && length <= 10) {
                while (result.toString().contains(n)) {
                    n = String.valueOf(random.nextInt(10));
                }
            }
            result.append(n);
        }
        return result.toString();
    }

    /**
     * 获取时间数据，加了同步锁
     *
     * @return 返回当前毫秒数
     */
    public static String getCurrentTimeMillis() {
        return String.valueOf(System.currentTimeMillis());
    }

    public static String MD5(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(s.getBytes(StandardCharsets.UTF_8));

            final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
            StringBuilder ret = new StringBuilder(bytes.length * 2);
            for (int i = 0; i < bytes.length; i++) {
                ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
                ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
            }
            return ret.toString();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 进行base64解码
     *
     * @param encodeString 编码后字符串
     * @return 解码后字符串
     */
    public static String base64Decode(String encodeString) {
        return new String(Base64.getDecoder().decode(encodeString));
    }

    /**
     * 进行base64编码
     *
     * @param str       原字符串
     * @param character 原字符串字符集
     * @return 编码后的字符串
     */
    public static String base64Encode(String str, String character) {
        try {
            return Base64.getEncoder().encodeToString(str.getBytes(character));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 集合转逗号分隔的字符串(已经去掉了最后的逗号)
     *
     * @param collection 集合
     * @return 逗号分隔的字符串
     */
    public static String collectionsToCommas(Collection<String> collection) {
        // 非空判断
        if (collection == null || collection.size() == 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        collection.forEach(i -> sb.append(i).append(","));
        // 去掉逗号并返回
        return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : null;
    }

    /**
     * 集合转逗号分隔的字符串(已经去掉了最后的逗号)
     *
     * @param collection 集合
     * @return 逗号分隔的字符串
     */
    public static <T, R> String collectionsToCommas(Collection<T> collection, Function<? super T, ? extends R> mapper) {
        // 非空判断
        if (collection == null || collection.size() == 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        collection.stream().map(mapper).forEach(i -> sb.append(i).append(","));
        // 去掉逗号并返回
        return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : null;
    }

    public static void main(String[] args) {
        logger.info(randomUUID());
        logger.info(randomUUIDUpperCase());
        logger.info(isEmpty("\n"));
        logger.info(isBlank("\n"));
        logger.info(randomByTime());
        logger.info(randomByTime2());
        logger.info(UUID.randomUUID());
        logger.info(base64Encode("943C47D756494E9190D9D1290BE20662", "utf-8"));
        logger.info(base64Decode("OTQzQzQ3RDc1NjQ5NEU5MTkwRDlEMTI5MEJFMjA2NjI="));
        logger.info(base64Encode("3718388895f92cb0805af289dcccfda0", "utf-8"));
        logger.info(base64Decode("MzcxODM4ODg5NWY5MmNiMDgwNWFmMjg5ZGNjY2ZkYTA="));
        logger.info(randomUUID(30));
        logger.info(base64Encode("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCOy7qQINT7h1xa14PFXhGNwreRZRRDYCI8rcRNRNSOKW1geEEJ/PZr1dBrTEhYzpfEiLQaaIsIzSMopCy0PrVZIy8xZRzcJ5tcd8fjuf8DqhtlILr/YMtfNEmvy4m0udB/65NQVsXGdLnly13Kdl/DF46FWvCeHpL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FornNAcEZrvkD0bY595tO4wdOCinHXp5lY9CDZnaPAAz/8Y5m/N12sBKlKwEa/L6V/18+XpY2rmGKMRdDKa6zbhQH6gE8Xqgz+d6SQaZEAuXtV2i4iKZGOhsoC30FpOzyFpN0VBvTRlpNuQ+NrY0a5PWryVAoGBAJOT9yrW+a0BtK2vXaBMnDkyNcQGFGM4oanDQS7vCQ7udtIANQlHWxxO0UojaouoN6VAv1zjfWACosR0rGhxByEN3WN7fZKILZJpLWVyXcNe9QKgV2Ef0P8o7tuXCEUZbylxggsr5WmXE+skdw3IJ78rDVr/6Hz90kZEc4ayhE/b", "utf-8"));
        logger.info(base64Encode("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4LwVChEscFkk7UcvyQuUjd58X0yenct2FHnJtc/l6xYMXqkWBmfglvAUETa9iuy4t0u1P0ZdsnuSFyVQcJeg6ZBDcxrn+BlSLiQvcWBvcVgY41dij0X7lOSD+hkOVeRBJHNwUpHyDgiL2MOklRjKmc6PxwSz5+vgefA4fhYs5fY0NncOzEhGxpP+SL10tvZn+jmwxT042v3Ly6+GBF2Bu7UnsZP5+AsD4EIebEFAekLzjKWWfAfB9s188JYGyIW5/eCOqXrXfbaDQ3Zz1+9uutIiklsWIFYOTASpACOv1PwAb2g0TXmNekJobHK8Yt024vesXbB27/mKLklLDOwJUwIDAQAB", "utf-8"));

        List<String> abc = Arrays.asList(new String[]{"asdf", "as1z5df", "a5z1sdf", "asz612df", "as634z6df", "a635zsdf", "as623z464df"});
        logger.info(Arrays.toString(abc.stream().map(String::length).filter(integer -> integer > 8).toArray()));

    }
}
